package com.rain.email.service.impl;

import com.rain.email.service.EmailSendService;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author xxq
 */
@Service
public class EmailSendServiceImpl implements EmailSendService {
    @Override
    public boolean send(String email) {
        Properties prop = new Properties();
        // 设置QQ邮件服务器
        prop.setProperty("mail.host", "smtp.163.com");
        // 邮件发送协议
        prop.setProperty("mail.transport.protocol", "smtp");
        // 需要验证用户名密码
        prop.setProperty("mail.smtp.auth", "true");

        // 创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("testemail_yian@163.com", "SQEFNTGRNOVTTUQK");
            }
        });
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);

        Transport ts = null;
        try {
            // 通过session得到transport对象
            ts = session.getTransport();
            // 使用邮箱的用户名和授权码连上邮件服务器
            ts.connect("smtp.163.com", "testemail_yian@163.com", "SQEFNTGRNOVTTUQK");
            // 创建邮件
            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            // 指明邮件的发件人
            message.setFrom(new InternetAddress("testemail_yian@163.com"));
            // 指明邮件的收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 邮件的标题
            message.setSubject("Rain注册验证码");
            // 邮件的文本内容
            // message.setContent("5656", "text/html;charset=UTF-8");
            message.setText("5656");
            // 发送邮件
            ts.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                assert ts != null;
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }

        return true;
    }
}
